package ipower.studentworks.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ClassUtils;
import ipower.configuration.ModuleDefine;
import ipower.configuration.ModuleSystem;
import ipower.configuration.ModuleSystemCollection;
import ipower.pageModel.TreeNode;
import ipower.studentworks.service.MenuService;
/**
 * 菜单服务实现类。
 * */
public class MenuServiceImpl implements MenuService {
	private static Logger logger = Logger.getLogger(MenuServiceImpl.class);
	private static Map<String, List<TreeNode>> mapNodeCache = Collections.synchronizedMap(new HashMap<String,List<TreeNode>>());
	private InputStream menuFileStream;
	
	@Override
	public void setMenuFile(String menuFile) {
		if(menuFile != null && !menuFile.isEmpty()){
			try {
				Resource rs = new ClassPathResource(menuFile, ClassUtils.getDefaultClassLoader());
				if(rs != null)
					this.menuFileStream = rs.getInputStream();
			} catch (IOException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public synchronized List<TreeNode> tree(String systemId) {
		if(this.menuFileStream != null && systemId != null && !systemId.isEmpty()){
			List<TreeNode> results = mapNodeCache.get(systemId);
			if(results == null || results.size() == 0){
				ModuleSystemCollection collection = ModuleSystemCollection.parse(this.menuFileStream);
				if(collection != null && collection.size() > 0){
					ModuleSystem ms = collection.item(systemId);
					if(ms != null && ms.getModules() != null && ms.getModules().size() > 0){
						results = new ArrayList<TreeNode>();
						for(ModuleDefine m : ms.getModules()){
							TreeNode n = this.createTree(m);
							if(n != null)
								results.add(n);
						}
						if(results.size() > 0) mapNodeCache.put(systemId, results);
					}
				}
			}
			return results;
		}
		return null;
	}

	private TreeNode createTree(ModuleDefine m){
		if(m != null){
			TreeNode node = new TreeNode();
			node.setId(m.getModuleID());
			node.setText(m.getModuleName());
			Map<String,Object> attributes = new HashMap<String,Object>();
			attributes.put("url", m.getModuleUri());
			node.setAttributes(attributes);
			if(m.getModules() != null && m.getModules().size() > 0){
				List<TreeNode> children = new ArrayList<TreeNode>();
				for(ModuleDefine d: m.getModules()){
					TreeNode tn = this.createTree(d);
					if(tn != null){
						children.add(tn);
					}
				}
				if(children.size() > 0){
					node.setChildren(children);
				}
			}
			return node;
		}
		return null;
	}
}